<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\service\report\kuaishou;

use app\enum\CommonEnum;
use app\enum\ReportRecordEnum;
use app\model\ClientAccountModel;
use app\model\ClientAccountOperationTimeModel;
use app\model\report\ReportRecordKsDayDataModel;
use app\model\report\ReportRecordKsHourDataModel;
use app\service\BaseService;
use app\service\report\ReportRecordDataService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

final class ProcessingDataService extends BaseService
{
    /**
     * 数据处理.
     */
    public static function processingData(array $params = [])
    {
        try {
            // excel模板
            $templates = json_decode($params['templates']['data'], true)[0]['data'];
            // 发送的时间点
            $sendHour = $params['sendTime'];
            // 发送的日期
            $sendDate = $params['sendDate'];
            $sendYesterdayDate = strtotime(strval($sendDate)) - 86400;
            $sendBeforeYesterdayDate = strtotime(strval($sendDate)) - (2 * 86400);
            // 发送的时间点数组
            $send_time = json_decode($params['send_time'], true);
            // 数据维度 1账户 2广告组 3广告计划
            $dimension = $params['dimension'];
            // 报表排序 1账户 2消耗
            $dataSort = $params['data_sort'];
            // 报表类型：1时报；2日报 (日报就是昨天的所有的数据，时报就是当天截止到时间点的数据)
            $report_date_type = $params['report_date_type'];
            // 折算比例
            $cash_cost_ratio = $params['templates']['cash_cost_ratio'];
            // 折后成本-折算比例
            $folding_convert_ratio = $params['templates']['folding_convert_ratio'];
            // 折后成本-选择的字段
            $folding_convert_field = $params['templates']['folding_convert_field'];
            // 选择的账户ID数组
            $advertiserIds = json_decode($params['templates']['adv_unit_plan_lists'], true) ?? [];
            // 自定义数据数组
            $custom_fields_name = $params['custom_fields_name'] ? json_decode($params['custom_fields_name'], true) : [];
            // 获取所有广告主的信息
            $advInfos = [];
            $productInfos = [];
            $advInfoss = (new ClientAccountModel())->alias('a')
                ->leftJoin(['habo_account_port' => 'b'], 'a.advertiser_id=b.advertiser_id')
                ->leftJoin(['habo_client_promotion_product' => 'c'], 'c.id=b.product_id')
                ->whereIn('a.advertiser_id', $advertiserIds)
                ->where('a.status', 1)
                ->field('a.advertiser_id,a.account_name,c.product_name')
                ->select()
                ->toArray();
            if (! empty($advInfoss)) {
                foreach ($advInfoss as $val) {
                    $advInfos[$val['advertiser_id']] = $val['account_name'];
                    $productInfos[$val['advertiser_id']] = $val['product_name'];
                }
            }
            $dataArr = [];
            $SecondStayCost = [];
            foreach ($templates as $rk => &$template) {
                // $templates[$rk] = array_filter($template);
                if ($rk >= 1) {
                    foreach ($template as $ck => &$data) {
                        if (! isset($data['v']) || isset($data['f'])) {
                            continue;
                        }
                        $templates[$rk][$ck] = array_filter($data);
                        if ($ck >= 1) {
                            $index = $rk . '_' . $ck;
                            $result = [];
                            if (strpos(strval($data['v']), ')]') || strpos(strval($data['v']), '[=') !== false || strpos(strval($data['v']), ':00')) {
                                // 获取今日或者昨日的条件
                                $dateType = ReportRecordDataService::getDateType(strval($data['v'])); // 日期类型
                                if (isset($template[0]['v'])) {
                                    $advertiserId = ReportRecordDataService::getAdvertiserIds($template[0]['v']); // 获取账户ID
                                }
                                $field = ReportRecordDataService::getFieldType(strval($data['v']), ReportRecordEnum::KS_MEDIA, $dateType); // 数据类型
                                if ($field == 'time') {
                                    if (! strpos($data['v'], '时间')) {
                                        $sendHour = intval(date('H', strtotime($data['v'])));
                                        $result[$index][$field] = $data['v'];
                                    } else {
                                        $result[$index][$field] = $sendHour . ':00';
                                    }
                                }
                                if ($field == 'date') {
                                    if ($dateType == 1) {
                                        $date = date('Y-m-d');
                                        $result[$index][$field] = $date;
                                    }
                                    if ($dateType == 2) {
                                        $date = date('Y-m-d', strtotime('-1 day'));
                                        $result[$index][$field] = $date;
                                    }
                                }
                                // echo $rk . '-' . $ck . '-' . $field . '----' . $data['v'] . PHP_EOL;
                                // 次留
                                if ($field == 'event_next_day_stay' || $field == 'event_next_day_stay_cost' || $field == 'event_next_day_stay_ratio') {
                                    if ($dateType == 1 || $dateType == 2) {
                                        if ($dateType == 1) { // 小时次留
                                            $statDate = date('Ymd', $sendYesterdayDate);
                                        } else { // 日次留
                                            $statDate = date('Ymd', $sendBeforeYesterdayDate);
                                        }
                                        // 获取次留数据
                                        $secondStay = self::getSecondStayHourData(intval($advertiserId), intval($statDate), $sendHour);
                                        $result[$index]['event_next_day_stay'] = $secondStay['event_next_day_stay'];
                                        $result[$index]['activation'] = $secondStay['activation'];
                                        $result[$index]['charge'] = $secondStay['charge'];
                                        $result[$index]['event_next_day_stay_cost'] = ! empty($result[$index]['event_next_day_stay']) ? round($result[$index]['charge'] / $result[$index]['event_next_day_stay'], 3) : 0; // 留存成本
                                        $result[$index]['event_next_day_stay_ratio'] = ! empty($result[$index]['activation']) ? round($result[$index]['event_next_day_stay'] / $result[$index]['activation'] * 100, 2) . '%' : '0%';
                                        // 数据整合
                                        $dataArr['event_next_day_stay_' . $ck][intval($advertiserId)] = $result[$index]['event_next_day_stay'] ?? 0;
                                        $dataArr['activation_' . $ck][intval($advertiserId)] = $result[$index]['activation'] ?? 0;
                                        $SecondStayCost[$ck][intval($advertiserId)] = $result[$index]['charge'] ?? 0;
                                    }
                                }
                                // 昨日同时段消耗、昨日同时段消耗环比
                                if ($field == 'yesterday_cost' || $field == 'yesterday_cost_rate') {
                                    if ($dateType == 1 || $dateType == 2) {
                                        // 昨日同时段消耗
                                        $yesterdayCostSum = self::getKsHourData(intval($sendYesterdayDate), $sendHour, intval($advertiserId), ReportRecordEnum::REPORT_DATE_TYPE_TIME, 'charge');
                                        $result[$index]['yesterday_cost'] = ! empty($yesterdayCostSum) ? $yesterdayCostSum : 0;
                                        // 当天同时段消耗
                                        if (empty($result[$index]['charge'])) {
                                            $result[$index]['charge'] = self::getKsHourData(intval($sendDate), $sendHour, intval($advertiserId), ReportRecordEnum::REPORT_DATE_TYPE_TIME, 'charge');
                                        }
                                        // 昨日同时段消耗环比
                                        $x = bcsub(strval($result[$index]['charge']), strval($result[$index]['yesterday_cost']), 3);
                                        $result[$index]['yesterday_cost_rate'] = ! empty($result[$index]['yesterday_cost']) ? round($x / $yesterdayCostSum * 100, 2) . '%' : '0%';
                                        // 数据整合
                                        $dataArr['yesterday_cost_' . $ck][intval($advertiserId)] = $result[$index]['yesterday_cost'];
                                    }
                                }

                                // 付费成本环比
                                if ($field == 'event_new_user_pay_ringgit') {
                                    if ($dateType == 1 || $dateType == 2) {
                                        // 昨日同时段新增付费人数成本
                                        $yesterdayActivePayCost = self::getKsDayData(intval($sendYesterdayDate), $sendHour, intval($advertiserId), ReportRecordEnum::REPORT_DATE_TYPE_DAY, 'event_new_user_pay_cost');
                                        $result[$index]['event_new_user_pay_cost_yesterday'] = ! empty($yesterdayActivePayCost) ? $yesterdayActivePayCost : 0;
                                        // 当天同时段新增付费人数成本
                                        if (empty($result[$index]['event_new_user_pay_cost'])) {
                                            $result[$index]['event_new_user_pay_cost'] = self::getKsHourData(intval($sendDate), $sendHour, intval($advertiserId), ReportRecordEnum::REPORT_DATE_TYPE_TIME, 'event_new_user_pay_cost');
                                        }
                                        // 付费成本环比
                                        $result[$index]['active_pay_ringgit'] = ! empty($result[$index]['active_pay_cost_yesterday']) ? round($result[$index]['event_new_user_pay_cost'] / $result[$index]['event_new_user_pay_cost_yesterday'] - 1, 2) : 0;
                                    }
                                }
                                // 优化师
                                if ($field == 'operation_name') {
                                    $result[$index]['operation_name'] = ClientAccountOperationTimeModel::alias('a')->leftJoin(['habo_staff' => 'b'], 'a.staff_id=b.id')->where('a.advertiser_id', $advertiserId)->whereNull('a.end_date')->value('staff_name');
                                }
                                // 广告主信息
                                if ($field == 'advertiser_id') {
                                    $result[$index]['advertiser_id'] = $advertiserId;
                                }
                                if ($field == 'account_name') {
                                    $result[$index]['account_name'] = ! empty($advInfos[$advertiserId]) ? $advInfos[$advertiserId] : '';
                                }
                                // 产品
                                if ($field == 'product_name') {
                                    $result[$index]['product_name'] = ! empty($productInfos[$advertiserId]) ? $productInfos[$advertiserId] : '';
                                }
                                // 代理商
                                if ($field == 'agent') {
                                    $result[$index]['agent'] = ReportRecordEnum::AGENT;
                                }
                                // 媒体
                                if ($field == 'media') {
                                    $result[$index]['media'] = ReportRecordEnum::KS_MEDIA_NAME;
                                }
                                // 折后消耗
                                if ($field == 'cash_cost') {
                                    if ($dateType == 1 || $dateType == 2) {
                                        if (empty($result[$index]['charge'])) {
                                            if ($dateType == 1) {
                                                $result[$index]['charge'] = self::getKsHourData(intval($sendDate), $sendHour, intval($advertiserId), $dateType, 'charge');
                                            }
                                            if ($dateType == 2) {
                                                $result[$index]['charge'] = self::getKsDayData(intval(date('Ymd', $sendYesterdayDate)), $sendHour, intval($advertiserId), $dateType, 'charge');
                                            }
                                        }
                                        $result[$index]['cash_cost'] = ! empty($cash_cost_ratio) ? round($result[$index]['charge'] / $cash_cost_ratio, 2) : 0;
                                        $dataArr['cash_cost_' . $ck][intval($advertiserId)] = $result[$index]['cash_cost'];
                                    }
                                    // 汇总数据
                                    if ($dateType == 3) {
                                        $result[$index]['cash_cost'] = array_sum($dataArr['cash_cost_' . $ck]);
                                    }
                                }
                                // 折后成本
                                if ($field == 'folding_convert') {
                                    if ($dateType == 1 || $dateType == 2) {
                                        if (empty($result[$index][$folding_convert_field])) {
                                            $result[$index][$folding_convert_field] = 0;
                                            if ($dateType == 1) {
                                                $resourceData = self::getKsHourResourceData(intval($sendDate), $sendHour, intval($advertiserId), $dateType);
                                            }
                                            if ($dateType == 2) {
                                                $statDate = date('Ymd', $sendYesterdayDate);
                                                $resourceData = self::getKsDayResourceData(intval($statDate), $sendHour, intval($advertiserId), $dateType);
                                            }
                                            if (isset(ReportRecordEnum::MEDIA_FIELD_VALUE_RULE[CommonEnum::KS_MEDIA][$folding_convert_field])) {
                                                $result[$index][$folding_convert_field] = ReportRecordDataService::getFieldValue($resourceData, ReportRecordEnum::MEDIA_FIELD_VALUE_RULE[CommonEnum::KS_MEDIA][$folding_convert_field]);
                                            } else {
                                                $result[$index][$folding_convert_field] = $resourceData[$folding_convert_field];
                                            }
                                        }
                                        $result[$index]['folding_convert'] = ! empty($folding_convert_ratio) ? round($result[$index][$folding_convert_field] / $folding_convert_ratio, 2) : 0;
                                        $dataArr['folding_convert_' . $ck][intval($advertiserId)] = $result[$index]['folding_convert'];
                                    }
                                    // 汇总数据
                                    if ($dateType == 3) {
                                        $result[$index]['folding_convert'] = array_sum($dataArr['folding_convert_' . $ck]);
                                    }
                                }
                                // 自定义数据
                                if (! empty($custom_fields_name)) {
                                    if ($dateType == 1 || $dateType == 2) {
                                        foreach ($custom_fields_name as $item) {
                                            if (empty($result[$index][$item['molecule']])) {
                                                if ($dateType == 1) {
                                                    $result[$index][$item['molecule']] = self::getKsHourData(intval($sendDate), $sendHour, intval($advertiserId), $dateType, $item['molecule']);
                                                }
                                                if ($dateType == 2) {
                                                    $result[$index][$item['molecule']] = self::getKsDayData(intval($sendYesterdayDate), $sendHour, intval($advertiserId), $dateType, $item['molecule']);
                                                }
                                            }
                                            if (empty($result[$index][$item['denominator']])) {
                                                if ($dateType == 1) {
                                                    $result[$index][$item['denominator']] = self::getKsHourData(intval($sendDate), $sendHour, intval($advertiserId), $dateType, $item['denominator']);
                                                }
                                                if ($dateType == 2) {
                                                    $result[$index][$item['denominator']] = self::getKsDayData(intval($sendYesterdayDate), $sendHour, intval($advertiserId), $dateType, $item['denominator']);
                                                }
                                            }
                                            $molecule = ! empty($result[$index][$item['molecule']]) ? str_replace('%', '', $result[$index][$item['molecule']]) : 0;
                                            $denominator = ! empty($result[$index][$item['denominator']]) ? str_replace('%', '', $result[$index][$item['denominator']]) : 0;
                                            $result[$index][$item['field']] = $denominator > 0 ? round($molecule / $denominator, 2) : 0;

                                            $dataArr[$item['molecule']][intval($advertiserId)] = $molecule;
                                            $dataArr[$item['denominator']][intval($advertiserId)] = $denominator;
                                        }
                                    }
                                    // 汇总数据
                                    if ($dateType == 3) {
                                        if (empty($result[$index][$field])) {
                                            foreach ($custom_fields_name as $cfnv) {
                                                $molecule = ! empty($result[$index][$cfnv['molecule']]) ? str_replace('%', '', $result[$index][$cfnv['molecule']]) : 0;
                                                $denominator = ! empty($result[$index][$cfnv['denominator']]) ? str_replace('%', '', $result[$index][$cfnv['denominator']]) : 0;
                                                $result[$index][$cfnv['field']] = $denominator > 0 ? round($molecule / $denominator, 2) : 0;
                                            }
                                        }
                                    }
                                }
                                // 今日数据
                                if ($dateType == 1) {
                                    if (! isset($result[$index][$field])) {
                                        $result[$index][$field] = 0;
                                        $resourceData = self::getKsHourResourceData(intval($sendDate), $sendHour, intval($advertiserId), $dateType);
                                        $result[$index][$field] = ! empty($resourceData[$field]) ? $resourceData[$field] : 0;
                                        $dataArr['data'][intval($advertiserId)] = $resourceData;
                                    }
                                }

                                // 昨日数据
                                if ($dateType == 2) {
                                    if (! isset($result[$index][$field])) {
                                        $result[$index][$field] = 0;
                                        $statDate = date('Ymd', $sendYesterdayDate);
                                        $resourceData = self::getKsDayResourceData(intval($statDate), $sendHour, intval($advertiserId), $dateType);
                                        $result[$index][$field] = ! empty($resourceData[$field]) ? $resourceData[$field] : 0;
                                        $dataArr['data'][intval($advertiserId)] = $resourceData;
                                    }
                                }
                                if ($dateType == 1 || $dateType == 2) {
                                    if (isset(ReportRecordEnum::MEDIA_FIELD_VALUE_RULE[CommonEnum::KS_MEDIA][$field]) && ! empty($resourceData)) {
                                        $result[$index][$field] = ReportRecordDataService::getFieldValue($resourceData, ReportRecordEnum::MEDIA_FIELD_VALUE_RULE[CommonEnum::KS_MEDIA][$field]);
                                    }
                                }
                                if ($dateType == 3) {
                                    if (! empty($dataArr['data'])) {
                                        $dataArrs = [];
                                        foreach ($dataArr['data'] as $subArray) {
                                            foreach ($subArray as $key => $value) {
                                                // 如果结果数组中已经有相同的键，且值不是字符串，将值相加
                                                if (array_key_exists($key, $dataArrs) && is_numeric($dataArrs[$key]) && is_numeric($value)) {
                                                    $dataArrs[$key] += $value;
                                                } else {
                                                    // 否则，将键值对添加到结果数组
                                                    $dataArrs[$key] = $value;
                                                }
                                            }
                                        }
                                        // 次留
                                        if ($field == 'event_next_day_stay' || $field == 'event_next_day_stay_cost' || $field == 'event_next_day_stay_ratio') {
                                            $result[$index]['event_next_day_stay_cost'] = ! empty($dataArr['event_next_day_stay']) ? round(array_sum($SecondStayCost[$ck]) / array_sum($dataArr['event_next_day_stay_' . $ck]), 3) : 0;
                                            $result[$index]['event_next_day_stay_ratio'] = ! empty($dataArr['activation_' . $ck]) ? round(array_sum($dataArr['event_next_day_stay_' . $ck]) / array_sum($dataArr['activation_' . $ck]) * 100, 2) . '%' : '0%';
                                            $result[$index]['event_next_day_stay'] = ! empty($dataArr['event_next_day_stay_' . $ck]) ? array_sum($dataArr['event_next_day_stay_' . $ck]) : 0;
                                        }
                                        // 昨日同时段消耗、昨日同时段消耗环比
                                        if ($field == 'yesterday_cost' || $field == 'yesterday_cost_rate') {
                                            // 昨日同时段消耗环比
                                            $x = bcsub(strval($dataArrs['charge']), strval(array_sum($dataArr['yesterday_cost_' . $ck])), 3);
                                            $result[$index]['yesterday_cost_rate'] = ! empty($dataArr['yesterday_cost_' . $ck]) ? round($x / array_sum($dataArr['yesterday_cost_' . $ck]) * 100, 2) . '%' : '0%';
                                            $result[$index]['yesterday_cost'] = ! empty($dataArr['yesterday_cost_' . $ck]) ? array_sum($dataArr['yesterday_cost_' . $ck]) : 0;
                                        }
                                        // 付费成本环比
                                        if ($field == 'event_new_user_pay_ringgit') {
                                            $result[$index]['active_pay_ringgit'] = ! empty($dataArrs['active_pay_cost_yesterday']) ? round($dataArrs['event_new_user_pay_cost'] / $dataArrs['event_new_user_pay_cost_yesterday'] - 1, 2) : 0;
                                        }
                                        if (! isset($result[$index][$field])) {
                                            if (isset(ReportRecordEnum::MEDIA_FIELD_VALUE_RULE[CommonEnum::KS_MEDIA][$field]) && ! empty($resourceData)) {
                                                $result[$index][$field] = ReportRecordDataService::getFieldValue($dataArrs, ReportRecordEnum::MEDIA_FIELD_VALUE_RULE[CommonEnum::OE_MEDIA][$field]);
                                            } else {
                                                $result[$index][$field] = $dataArrs[$field];
                                            }
                                        }
                                    }
                                }
                                $templates[$rk][$ck]['m'] = $result[$index][$field];
                                $templates[$rk][$ck]['v'] = $result[$index][$field];
                            }
                        }
                    }
                }
            }
            return $templates;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取小时次留.
     * @return int[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getSecondStayHourData(int $advertiserId = 0, int $statDate = 0, int $statHour = 0, int $report_date_type = 1): array
    {
        $data = (new ReportRecordKsHourDataModel())
            ->where('advertiser_id', $advertiserId)
            ->where('stat_date', $statDate)
            ->where('date_type', $report_date_type)
            ->select();
        $eventNextDayStaySum = 0;
        $chargeSum = 0;
        $activationSum = 0;
        if ($data) {
            $data = $data->toArray();
            foreach ($data as $val) {
                $val['data_content'] = json_decode($val['data_content'], true);
                $chargeSum += $val['data_content']['charge']; // 消耗
                $activationSum += $val['data_content']['activation']; // 激活数
                if ($statHour >= $val['stat_hour']) {
                    $eventNextDayStaySum += $val['data_content']['event_next_day_stay']; // 次留数
                }
            }
        }
        return [
            'event_next_day_stay' => $eventNextDayStaySum,
            'charge' => $chargeSum,
            'activation' => $activationSum,
        ];
    }

    /**
     * 获取小时整合数据.
     * @param int $statDate 日期
     * @param int $sendHour 小时
     * @param int $advertiserId 账户ID
     * @param int $dateType 日期类型
     * @return array|bool
     */
    public static function getKsHourResourceData(int $statDate = 0, int $sendHour = 0, int $advertiserId = 0, int $dateType = 1)
    {
        try {
            $data = (new ReportRecordKsHourDataModel())
                ->where('advertiser_id', $advertiserId)
                ->where('stat_date', $statDate)
                ->where('stat_hour', '<=', $sendHour)
                ->where('date_type', $dateType)
                ->order('stat_hour ASC')
                ->field('data_content')
                ->select()->toArray();
            $result = [];
            foreach ($data as $subArray) {
                $subArray = json_decode($subArray['data_content'], true);
                foreach ($subArray as $key => $value) {
                    // 如果结果数组中已经有相同的键，且值不是字符串，将值相加
                    if (array_key_exists($key, $result) && is_numeric($result[$key]) && is_numeric($value)) {
                        $result[$key] += $value;
                    } else {
                        // 否则，将键值对添加到结果数组
                        $result[$key] = $value;
                    }
                }
            }
            return $result;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取天数据.
     * @param int $statDate 日期
     * @param int $sendHour 小时
     * @param int $advertiserId 账户ID
     * @param int $dateType 日期类型
     * @return array|bool
     */
    public static function getKsDayResourceData(int $statDate = 0, int $sendHour = 0, int $advertiserId = 0, int $dateType = 1)
    {
        $where = [
            'stat_date' => $statDate,
            'stat_hour' => $sendHour,
            'advertiser_id' => $advertiserId,
            'date_type' => $dateType,
        ];
        $result = [];
        try {
            $data = (new ReportRecordKsDayDataModel())->where($where)->field('data_content')->select()->toArray();
            foreach ($data as $subArray) {
                $subArray = json_decode($subArray['data_content'], true);
                foreach ($subArray as $key => $value) {
                    // 如果结果数组中已经有相同的键，且值不是字符串，将值相加
                    if (array_key_exists($key, $result) && is_numeric($result[$key]) && is_numeric($value)) {
                        $result[$key] += $value;
                    } else {
                        // 否则，将键值对添加到结果数组
                        $result[$key] = $value;
                    }
                }
            }
            return $result;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取小时数据.
     * @param int $statDate 日期
     * @param int $sendHour 小时
     * @param int $advertiserId 账户ID
     * @param int $dateType 日期类型
     * @return array|bool
     */
    public static function getKsHourData(int $statDate = 0, int $sendHour = 0, int $advertiserId = 0, int $dateType = 1, string $field = '')
    {
        try {
            $data = (new ReportRecordKsHourDataModel())
                ->where('advertiser_id', $advertiserId)
                ->where('stat_date', $statDate)
                ->where('stat_hour', '<=', $sendHour)
                ->where('date_type', $dateType)
                ->order('stat_hour ASC')
                ->field('data_content')
                ->select();
            $sum = 0;
            if ($data) {
                $data = $data->toArray();
                foreach ($data as $v) {
                    $v = json_decode($v['data_content'], true);
                    $sum += $v[$field];
                }
            }
            return $sum;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取天数据.
     * @param int $statDate 日期
     * @param int $sendHour 小时
     * @param int $advertiserId 账户ID
     * @param int $dateType 日期类型
     * @return array|bool
     */
    public static function getKsDayData(int $statDate = 0, int $sendHour = 0, int $advertiserId = 0, int $dateType = 1, string $field = '')
    {
        $where = [
            'stat_date' => $statDate,
            'stat_hour' => $sendHour,
            'advertiser_id' => $advertiserId,
            'date_type' => $dateType,
        ];
        try {
            $data = (new ReportRecordKsDayDataModel())->where($where)->column('data_content');
            foreach ($data as $v) {
                $value = json_decode($v, true);
            }
            return ! empty($value[$field]) ? $value[$field] : 0;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}
